from rest_framework import serializers
from goods.models import SKU

class UserSkuCartSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label="商品编号",required=True)
    count = serializers.IntegerField(label="商品数量",required=True)
    selected = serializers.BooleanField(label="选中状态",default=True,required=False)


    def validate(self, attrs):
        #1,获取商品编号,数量
        sku_id = attrs["sku_id"]
        count = attrs["count"]

        #2,查询商品对象
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            raise serializers.ValidationError("商品不存在")

        #3,判断商品的库存是否大于,传递的count
        if count > sku.stock:
            raise serializers.ValidationError("库存不足")

        #4,返回
        return attrs


class UserSkuCartListSerializer(serializers.ModelSerializer):
    count = serializers.IntegerField(label="商品数量")
    selected = serializers.BooleanField(label="选中状态")
    class Meta:
        model = SKU
        fields = ("id","name","price","selected","default_image_url","count")


class DeleteCartSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label="商品编号",required=True)

    def validate_sku_id(self, value):
        #1,获取商品对象
        try:
            sku = SKU.objects.get(id=value)
        except Exception as e:
            raise serializers.ValidationError("商品不存在")

        #2,返回
        return value